package controllers

import (
	"encoding/json"

	"gitee.com/lzqysoft/ilive/libs"
	"gitee.com/lzqysoft/ilive/libs/aes"
	//	"gitee.com/lzqysoft/ilive/common/log"
	m "gitee.com/lzqysoft/ilive/models"
	"strconv"
	"time"

	"github.com/astaxie/beego"
)

//自定义通用controller
type CommonController struct {
	beego.Controller
	IsLogin     bool
	tokenString string
	user        *m.User
}

var Ssdbp libs.SsdbProvider

//检查权限
func init() {
	//	if er := Ssdbp.InitSsdb(); er != nil {
	//		log.Error("err is :", er)
	//	}
	//	m.CheckAccessAndRegisterRes()
	beego.InsertFilter("/gitee.com/lzqysoft/ilive/*", beego.BeforeRouter, Check)

}

//返回客户端数据结构
//正确code：0，Status：200
type Jdata struct {
	Code    int         `json:"code"`
	Token   string      `json:"token"`
	Message string      `json:"message"`
	Jdata   interface{} `json:"jdata"` //返回数据。加密
}

// 准备方法
func (c *CommonController) Prepare() {
	// Setting properties.
	user, ts := c.GetUserinfo()
	c.user = user
	c.IsLogin = true
	c.tokenString = ts
	//	c.Dlog("活动日志：访问了"+c.Ctx.Input.URL(), user.Id, 3)
	userprof, _ := m.GetUserprofById(user.Id)
	userprof.Logincount = userprof.Logincount + 1
	userprof.Loginip = c.Ctx.Input.IP()
	userprof.Logintime = time.Now()
	m.UpdateUserprofById(userprof)

}

// json格式返回错误码.
func (base *CommonController) RetError(e *ControllerError) {
	if mode := beego.AppConfig.String("runmode"); mode == "prod" {
		e.DevInfo = ""
	}
	//	base.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
	//	base.Ctx.Output.Header("Content-Encoding", "gzip")
	base.Ctx.ResponseWriter.WriteHeader(e.Status)
	beego.Debug("返回错误:", e)
	base.Data["json"] = e
	base.ServeJSON()
	base.StopRun()
}

// json格式返回正确值
func (base *CommonController) RetSuccess(data interface{}, tokens ...string) {
	//	base.Ctx.Output.Header("Content-Type", "application/json; charset=utf-8")
	//	base.Ctx.ResponseWriter.WriteHeader(e.Status)
	adata, err := base.AesEncode(data)
	if err != nil {
		base.RetError(ErrAes)
	}
	var jdata Jdata
	if len(tokens) > 0 {
		jdata.Token = tokens[0]
	} else {
		jdata.Token = base.tokenString
	}

	jdata.Code = 0
	jdata.Message = "操作成功"

	jdata.Jdata = adata
	base.Data["json"] = jdata
	base.ServeJSON()

	base.StopRun()
}

//写入日志
func (c *CommonController) Dlog(opa string, oid int64, tp ...int64) error {
	var log m.Log
	user, _ := c.GetUserinfo()
	log.UserId = user.Id
	log.Lon = 0
	log.Lat = 0
	log.Address = "-"
	log.UserName = user.Name
	if len(tp) > 0 {
		log.Type = tp[0]
	} else {
		log.Type = 1
	}
	log.Ip = c.Ctx.Input.IP()
	org, err := m.GetOrganizationById(user.Organization.Id)
	if err != nil {
		c.RetError(ErrNoUser)
	}
	log.OrgId = org.Id
	log.OrgName = org.Name
	log.Contect = log.UserName + ",操作为" + opa + ", id 为：" + strconv.FormatInt(oid, 10)
	log.Status = 1
	log.Creater = log.UserName
	log.Ctime = time.Now()
	log.Updater = log.Creater
	log.Utime = log.Ctime
	_, err = m.AddLog(&log)
	return err
}

//json数据aes加密
func (c *CommonController) AesEncode(plantText interface{}) (string, error) {
	tokenstring := c.Ctx.Input.Header("Authorization")
	key := []byte(libs.Substr(tokenstring, 5, 16))
	jp, _ := json.Marshal(plantText)
	v, err := aes.AesEncrypt(jp, key, key)
	return v, err
}

//json数据aes解密
func (c *CommonController) AesDecode(cipherstring string) (interface{}, error) {
	tokenstring := c.Ctx.Input.Header("Authorization")
	//	bc := []byte(cipherstring)
	key := []byte(libs.Substr(tokenstring, 5, 16))
	v, err := aes.AesDecrypt(cipherstring, key, key)
	var s interface{}
	err = json.Unmarshal(v, &s)
	return s, err
}

//获取用户信息
func (c *CommonController) GetUserinfo() (*m.User, string) {
	jcliem, ts, err := c.Getjwt()
	if err != nil {
		c.RetError(ErrToken)
	}
	uid := jcliem.Userid
	user, err := m.GetUserById(uid)
	if err != nil {
		c.RetError(ErrNoUser)
	}
	return user, ts
}
